package org.jeecg.modules.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * B端用户
 *
 * @Author scott
 * @since 2023-02-20
 */
@Api(tags="B端用户")
@Slf4j
@RestController
@RequestMapping("/sys/business/user")
public class SysBusinessUserController {

	@Autowired
	private ISysUserService sysUserService;

    //==========================================================后台====================================================
    /**
     * 获取用户列表数据
     * @param user
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value="B端用户-分页列表查询", notes="B端用户-分页列表查询")
    @GetMapping(value = "/list")
	public Result<IPage<SysUser>> queryPageList(SysUser user,@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,HttpServletRequest req) {
		Result<IPage<SysUser>> result = new Result<IPage<SysUser>>();
		QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(user, req.getParameterMap());

        //只查询B端用户
        queryWrapper.eq("user_type",3);
		Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
		IPage<SysUser> pageList = sysUserService.page(page, queryWrapper);

		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}

    /**
     * 添加B端用户
     * @param user
     * @return
     */
    @AutoLog(value = "B端用户-添加")
    @ApiOperation(value="B端用户-添加", notes="B端用户-添加")
    @PostMapping(value = "/add")
	public Result<?> add(@RequestBody SysUser user) {
        //判断用户是否已存在
        SysUser sysUser = sysUserService.getOne(QueryGenerator.initQueryWrapper(new SysUser(),null).lambda()
                .eq(SysUser::getUsername,user.getUsername()),false);
        if(oConvertUtils.isNotEmpty(sysUser)){
            if(sysUser.getUserType() == 3){
                return Result.ok("10001",sysUser.getId());
            }else {
                return Result.error("手机号已被使用！");
            }
        }

        String salt = oConvertUtils.randomGen(8);
        user.setSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(user.getPassword(), salt);
        user.setPassword(passwordEncode);
        user.setPhone(user.getUsername());
        user.setStatus(1);
        user.setDelFlag(CommonConstant.DEL_FLAG_0);
        user.setUserType(3);
        // 保存用户走一个service 保证事务
        sysUserService.saveUser(user, null);
		return Result.ok("0",user.getId());
	}

    /**
     *  编辑
     *
     * @param user
     * @return
     */
    @AutoLog(value = "B端用户-编辑", dataType = 2)
    @ApiOperation(value="B端用户-编辑", notes="B端用户-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<?> edit(@RequestBody SysUser user) {
        //判断用户是否已存在
        SysUser sysUser = sysUserService.getOne(QueryGenerator.initQueryWrapper(new SysUser(),null).lambda()
                .eq(SysUser::getUsername,user.getUsername()).ne(SysUser::getId,user.getId()),false);
        if(oConvertUtils.isNotEmpty(sysUser)){
            if(sysUser.getUserType() == 3){
                return Result.ok("10001",sysUser.getId());
            }else {
                return Result.error("手机号已被使用！");
            }
        }
        sysUserService.updateById(user);
        return Result.ok("0",user.getId());
	}

    /**
     * 删除
     */
    @AutoLog(value = "B端用户-删除")
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        sysUserService.delUser(id);
        return Result.ok("0",id);
    }

    /**
     * 获取被逻辑删除的用户列表，无分页
     *
     * @return logicDeletedUserList
     */
    @GetMapping("/recycleBin")
    public Result getRecycleBin() {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserType, 3);
        List<SysUser> logicDeletedUserList = sysUserService.queryLogicDeleted(wrapper);
        return Result.ok(logicDeletedUserList);
    }
    //==========================================================后台====================================================

    //==========================================================中台====================================================
    /**
     * 获取用户列表数据
     * @param user
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value="中台-B端用户管理-分页列表查询", notes="中台-B端用户管理-分页列表查询")
    @GetMapping(value = "/listMiddle")
    public Result<IPage<SysUser>> queryPageListMiddle(SysUser user,@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                      @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,HttpServletRequest req) {
        Result<IPage<SysUser>> result = new Result<IPage<SysUser>>();
        QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(user, req.getParameterMap());
        //查询当前租户下的B端用户
        queryWrapper.lambda().eq(SysUser::getUserType,3);
        queryWrapper.lambda().in(SysUser::getRelTenantIds, TokenUtils.getLoginUser().getRelTenantIds());
        Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
        IPage<SysUser> pageList = sysUserService.page(page, queryWrapper);

        result.setSuccess(true);
        result.setResult(pageList);
        log.info(pageList.toString());
        return result;
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @AutoLog(value = "中台-B端用户管理-添加")
    @ApiOperation(value="中台-B端用户管理-添加", notes="中台-B端用户管理-添加")
    @PostMapping(value = "/addMiddle")
    public Result<?> addMiddle(@RequestBody SysUser user) {
        String salt = oConvertUtils.randomGen(8);
        user.setSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(user.getPassword(), salt);
        user.setPassword(passwordEncode);
        user.setPhone(user.getUsername());
        user.setStatus(1);
        user.setDelFlag(CommonConstant.DEL_FLAG_0);
        //用户表字段org_code不能在这里设置他的值
        user.setOrgCode(null);
        user.setUserType(3);
        //当前登录用户
        LoginUser loginUser = TokenUtils.getLoginUser();
//        user.setNickname(loginUser.getNickname());
//        user.setAvatar(loginUser.getAvatar());
        user.setRelTenantIds(loginUser.getRelTenantIds());//保存当前登录用户的租户信息
        // 保存用户走一个service 保证事务
        sysUserService.saveBusinessUser(user);
        return Result.ok("添加成功！");
    }

    /**
     *  编辑用户
     *
     * @param user
     * @return
     */
    @AutoLog(value = "中台-B端用户管理-编辑", dataType = 2)
    @ApiOperation(value="中台-B端用户管理-编辑", notes="中台-B端用户管理-编辑")
    @RequestMapping(value = "/editMiddle", method = {RequestMethod.PUT,RequestMethod.POST})
    public Result<?> editMiddle(@RequestBody SysUser user) {
        sysUserService.editBusinessUser(user);
        return Result.OK("编辑成功!");
    }

    /**
     * 获取被逻辑删除的用户列表，无分页
     *
     * @return logicDeletedUserList
     */
    @GetMapping("/recycleBinMiddle")
    public Result recycleBinMiddle() {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserType, 3);
        wrapper.in(SysUser::getRelTenantIds, TokenUtils.getLoginUser().getRelTenantIds());
        List<SysUser> logicDeletedUserList = sysUserService.queryLogicDeleted(wrapper);
        return Result.ok(logicDeletedUserList);
    }

    /**
     * 根据B端用户ID查询绑定的商户id
     * @param userId
     * @return
     */
    @GetMapping("/queryBusinessIdByUserIdB")
    public Result queryBusinessIdByUserIdB(@RequestParam(name="userId",required=true) String userId) {
        return Result.ok(sysUserService.queryBusinessIdByUserIdB(userId));
    }
    //==========================================================中台====================================================

}
